package com.alibaba.algo.apiimpl.user;

import com.alibaba.algo.annotation.OperateLogAnnotation;
import com.alibaba.algo.constants.Constants;
import com.alibaba.algo.cooperation.common.BaseResult;
import com.alibaba.algo.cooperation.feign.vo.req.SelectOrgUserEmployeeVO;
import com.alibaba.algo.cooperation.usercomponent.service.user.SysUserService;
import com.alibaba.algo.cooperation.usercomponent.vo.req.user.*;
import com.alibaba.algo.cooperation.usercomponent.vo.res.user.*;
import com.alibaba.algo.core.base.YesOrNo;
import com.alibaba.algo.core.exception.BaseException;
import com.alibaba.algo.domain.user.*;
import com.alibaba.algo.entity.user.*;
import com.alibaba.algo.enums.OperateTypeEnum;
import com.alibaba.algo.enums.ResourceTypeEnum;
import com.alibaba.algo.enums.SysUserPassWdSaltEnum;
import com.alibaba.algo.enums.SysUserStateEnum;
import com.alibaba.algo.exception.BaseErrorCode;
import com.alibaba.algo.exception.SysEmployeeErrorCode;
import com.alibaba.algo.exception.SysUserEmployeeErrorCode;
import com.alibaba.algo.exception.SysUserErrorCode;
import com.alibaba.algo.utils.AESUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 类SysUserServiceImpl.java的实现描述：用户表 serviceimpl
 *
 * @author nieganggang 2021-03-12 16:08:17
 */
@Slf4j
@RestController
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserDomain sysUserDomain;

    @Autowired
    private SysRoleResourceActionDomain sysRoleResourceActionDomain;

    @Autowired
    private SysUserEmployeeDomain sysUserEmployeeDomain;

    @Autowired
    private SysUserRoleDomain sysUserRoleDomain;

    @Resource
    private SysUserEmployeeServiceImpl sysUserEmployeeService;

    @Resource
    private SysUserRoleServiceImpl sysUserRoleService;

    @Resource
    private SysEmployeeDomain sysEmployeeDomain;

    @Resource
    private SysOrgDomain sysOrgDomain;

    @Resource
    private SysEmployeeOrgDomain sysEmployeeOrgDomain;

    @Resource
    private SysPositionDomain sysPositionDomain;

    @Resource
    private SysEmployeePositionDomain sysEmployeePositionDomain;

    @Resource
    private SysUserAppDomain sysUserAppDomain;

    @Resource
    private SysRoleDomain sysRoleDomain;

    @Resource
    private SysUserCacheServiceImpl sysUserCacheService;

    @Resource
    SysLabelOrgEmployeeDomain sysLabelOrgEmployeeDomain;

    /**
     * @param vo
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public BaseResult insert(SaveUserRequestVO vo) {
        if (StringUtils.isEmpty(vo.getUserAccount()) || CollectionUtils.isEmpty(vo.getRoleIdList()) || StringUtils.isEmpty(vo.getUserName())) {
            throw new BaseException(SysUserErrorCode.MISSING_REQUIRED_FIELD.getCode(), SysUserErrorCode.MISSING_REQUIRED_FIELD.getMessage());
        }
        // 校验用户账号、手机号 去重
        this.checkUserInfoForInsert(vo.getUserAccount(), vo.getMobilePhone(), vo.getEmployeeId(), vo.getPasswd());
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(vo, sysUser);
        // 加密密码
        sysUser.setPasswd(SysUserPassWdSaltEnum.encrypt(vo.getPasswd()));
        SysUser sysUserLogicDeleted = sysUserDomain.getByUserAccountDefaultAll(vo.getUserAccount(), YesOrNo.Y.name());
        if (null != sysUserLogicDeleted) {
            sysUser.setId(sysUserLogicDeleted.getId());
            sysUser.setGmtModified(LocalDateTime.now());
            sysUser.setIsDeleted(YesOrNo.N.name());
            sysUser.setUserState(SysUserStateEnum.ACTIVATE.getValue());
            sysUserDomain.updateByIdWithEmptyProperties(sysUser);
        } else {
            sysUserDomain.insert(sysUser);
        }
        //增加登录权限sys_user_app
        //mom
        SysUserApp momSysUserApp = new SysUserApp();
        momSysUserApp.setUserId(sysUser.getId());
        momSysUserApp.setAppCode(Constants.APP_MOM);
        sysUserAppDomain.insert(momSysUserApp);
        //cmos
        SysUserApp cmosSysUserApp = new SysUserApp();
        cmosSysUserApp.setUserId(sysUser.getId());
        cmosSysUserApp.setAppCode(Constants.APP_CMOS);
        sysUserAppDomain.insert(cmosSysUserApp);
        Long userId = sysUser.getId();
        Long employeeId = vo.getEmployeeId();
        // 员工和用户的关联关系
        if (!ObjectUtils.isEmpty(employeeId)) {
            sysUserEmployeeService.insert(userId, employeeId);
        }
        // 用户和角色的关联关系
        for (Long roleId : vo.getRoleIdList()) {
            sysUserRoleService.insert(userId, roleId);
        }
        return BaseResult.buildSuccess(userId);
    }

    /**
     * 从SAP同步用户信息时，没有角色信息
     */
    @Override
    @OperateLogAnnotation(resouceType = ResourceTypeEnum.SYNC_USER_EMPLOYEE, operateType = OperateTypeEnum.INSERT)
    public BaseResult insertForSync(SaveUserRequestForSyncVO vo) {
        if (StringUtils.isEmpty(vo.getUserAccount()) || StringUtils.isEmpty(vo.getUserName())) {
            throw new BaseException(SysUserErrorCode.MISSING_REQUIRED_FIELD.getCode(), SysUserErrorCode.MISSING_REQUIRED_FIELD.getMessage());
        }

        Long employeeId = insertSysUserAndEmployeeForSync(vo);
        //组织岗位及关联关系通过其他接口同步
        //insertSysOrgAndPositionForSync(vo,employeeId);
        return BaseResult.buildSuccess();
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Long insertSysUserAndEmployeeForSync(SaveUserRequestForSyncVO vo) {
        //校验账号唯一性
        checkUserInfoForInsert(vo.getUserAccount(), null, null, null);
        //校验工号唯一性
        if (!org.springframework.util.StringUtils.isEmpty(vo.getEmployeeCode())) {
            SysEmployee userCode = new SysEmployee();
            userCode.setEmployeeCode(vo.getEmployeeCode());
            List<SysEmployee> sysEmployeeList = sysEmployeeDomain.listByPara(userCode, null);
            if (!CollectionUtils.isEmpty(sysEmployeeList)) {
                throw new BaseException(SysEmployeeErrorCode.EMPLOYEE_CODE_REPEAT.getCode(), SysEmployeeErrorCode.EMPLOYEE_CODE_REPEAT.getMessage());
            }
        }
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(vo, sysUser);
        try {
            String passWordPlainText = AESUtils.decryptByComac(vo.getPasswd(), AESUtils.keySeed);
            // 加密密码
            sysUser.setPasswd(SysUserPassWdSaltEnum.encrypt(passWordPlainText));
        } catch (Exception e) {
            log.error("insertSysUserAndEmployeeForSync decryptByComac error:{}", e.getMessage());
        }
        try {
            sysUser.setCreator(Constants.ORIGIN_SAP);
            int insertUserResult = sysUserDomain.insert(sysUser);
            log.debug("SysUserServiceImpl insertSysUserAndEmployeeForSync() insert sysUser,result:{}", insertUserResult);
            //增加登录权限sys_user_app
            //mom
            insertUser(sysUser, Constants.APP_MOM);
            //cmos
            insertUser(sysUser, Constants.APP_CMOS);
            //赋予普通用户登录权限
            SysRole param = new SysRole();
            //mom common user
            param.setAppCode("MOM");
            param.setRoleCode("commonMOM");
            insertRole(param, sysUser);
            //cmos common user
            param.setAppCode("CMOS");
            param.setRoleCode("commonCMOS");
            insertRole(param, sysUser);
            //cmos普通用户（已存在数据）
            param.setAppCode("CMOS");
            param.setRoleCode("common_user");
            insertRole(param, sysUser);
        } catch (Exception e) {
            sysUser = sysUserDomain.getByUserAccount(vo.getUserAccount());
            log.error("SysUserServiceImpl insertSysUserAndEmployeeForSync() insert sysUser error:{}", e.getMessage());
        }
        SysEmployee employee = new SysEmployee();
        BeanUtils.copyProperties(vo, employee);
        if (employee.getEmployeeType() == null) {
            //默认为合同制员工
            employee.setEmployeeType(1L);
        }
        if (ObjectUtils.isEmpty(employee.getEmployeeCode())) {//sys_emplyee表employ_code必填
            employee.setEmployeeCode("0");
        }
        try {
            employee.setCreator(Constants.ORIGIN_SAP);
            int insertEmployeeResult = sysEmployeeDomain.insert(employee);
            log.debug("SysUserServiceImpl insertSysUserAndEmployeeForSync() insert sysEmployee,result:{}", insertEmployeeResult);
        } catch (Exception e) {
            employee = sysEmployeeDomain.selectByEmployeeCode(employee.getEmployeeCode());
            log.error("SysUserServiceImpl insertSysUserAndEmployeeForSync() insert sysEmployee error:{}", e.getMessage());
        }
        Long userId = sysUser.getId();
        Long employeeId = employee.getId();
        SysUserEmployee sysUserEmployee = new SysUserEmployee();
        sysUserEmployee.setUserId(userId);
        sysUserEmployee.setEmployeeId(employeeId);
        sysUserEmployee.setCreator(Constants.ORIGIN_SAP);
        try {
            // 员工和用户的关联关系
            int insertUserEmployeeResult = sysUserEmployeeDomain.insert(sysUserEmployee);
            log.debug("SysUserServiceImpl insertSysUserAndEmployeeForSync() insert sysUserEmployee,result:{}", insertUserEmployeeResult);
        } catch (Exception e) {
            sysUserEmployee.setModifier(Constants.ORIGIN_SAP);
            sysUserEmployee.setGmtModified(LocalDateTime.now());
            sysUserEmployeeDomain.updateSysUserEmployeeByUserId(sysUserEmployee);
            log.error("SysUserServiceImpl insertSysUserAndEmployeeForSync() insert sysUserEmployee error:{}", e.getMessage());
        }
        return employeeId;
    }

    private void insertUser(SysUser sysUser, String appMom) {
        SysUserApp momSysUserApp = new SysUserApp();
        momSysUserApp.setUserId(sysUser.getId());
        momSysUserApp.setAppCode(appMom);
        momSysUserApp.setCreator(Constants.ORIGIN_SAP);
        sysUserAppDomain.insert(momSysUserApp);
    }

    private void insertRole(SysRole param, SysUser sysUser) {
        List<SysRole> roleList = sysRoleDomain.getRoles(param, null);
        if (!ObjectUtils.isEmpty(roleList)) {
            //cmos普通用户角色
            Long roleId = roleList.get(0).getId();
            SysUserRole cmosUserRole = new SysUserRole();
            cmosUserRole.setRoleId(roleId);
            cmosUserRole.setUserId(sysUser.getId());
            cmosUserRole.setCreator(Constants.ORIGIN_SAP);
            sysUserRoleDomain.insert(cmosUserRole);
        }
    }

    public void insertSysOrgAndPositionForSync(SaveUserRequestForSyncVO vo, Long employeeId) {
        if (null == employeeId) {
            return;
        }
        // 用户和组织的关联关系 单条记录
        List<String> orgCodeList = vo.getOrgCodeList();
        if (orgCodeList != null) {
            for (String orgCode : orgCodeList) {
                SysOrg sysOrg = sysOrgDomain.selectByOrgCode(orgCode);
                SysEmployeeOrg temp = new SysEmployeeOrg();
                temp.setEmployeeId(employeeId);
                if (!ObjectUtils.isEmpty(sysOrg) && !ObjectUtils.isEmpty(sysOrg.getId())) {
                    temp.setOrgId(sysOrg.getId());
                } else {//未获取到组织信息
                    return;
                }
                if (StringUtils.isEmpty(vo.getIsPrimaryOrg())) {//增量接口
                    AtomicBoolean primaryOrgFlag = new AtomicBoolean(false);
                    if (!ObjectUtils.isEmpty(vo.getOrgList())) {
                        vo.getOrgList().forEach(item -> {
                            if (orgCode.equals(item.getOrgCode()) && "Y".equals(item.getIsPrimaryOrg())) {
                                primaryOrgFlag.set(true);
                            }
                            if (orgCode.equals(item.getOrgCode())) { //人员在该组织下的排序位
                                temp.setOrderNum(ObjectUtils.isEmpty(item.getOrderNum()) ? "1" : String.valueOf(item.getOrderNum()));
                            }
                        });
                    }
                    if (primaryOrgFlag.get()) {
                        temp.setIsPrimaryOrg("Y");
                    } else {
                        temp.setIsPrimaryOrg("N");
                    }
                } else {//全量接口
                    temp.setIsPrimaryOrg(vo.getIsPrimaryOrg());
                }
                //人员在该组织下的排序位 为空给定默认值
                if (StringUtils.isEmpty(temp.getOrderNum())) {
                    temp.setOrderNum("1");
                }
                try {
                    temp.setCreator(Constants.ORIGIN_SAP);
                    int insertEmployeeOrgResult = sysEmployeeOrgDomain.insert(temp);
                    log.debug("SysUserServiceImpl insertSysOrgAndPositionForSync() insert sysEmployeeOrg,result:{}", insertEmployeeOrgResult);
                } catch (Exception e) {
                    //方法可根据employeeId做更新操作
                    temp.setModifier(Constants.ORIGIN_SAP);
                    sysEmployeeOrgDomain.updateById(temp);
                    log.error("SysUserServiceImpl insertSysOrgAndPositionForSync() insert sysEmployeeOrg,error:{}", e.getMessage());
                }
                //岗位信息
                SysPosition sysPosition = new SysPosition();
                BeanUtils.copyProperties(vo, sysPosition);
                sysPosition.setName(vo.getPosName());
                sysPosition.setIsPrimary(1L);//该字段废弃，但必填，1-为主岗，与其他表不同，需注意
                sysPosition.setOrgId(sysOrg.getId());
                //岗位没有排序，org_sort岗位排序字段为空，不设值
                if (null != sysOrg.getId() && !ObjectUtils.isEmpty(sysPosition.getName()) && "Y".equals(temp.getIsPrimaryOrg())) {//参数中岗位为主岗
                    try {
                        sysPosition.setCreator(Constants.ORIGIN_SAP);
                        SysPosition sysPositionFromDB = sysPositionDomain.getOne(sysPosition);
                        if (!ObjectUtils.isEmpty(sysPositionFromDB)) {
                            sysPosition = sysPositionFromDB;
                        } else {
                            sysPositionDomain.insert(sysPosition);
                        }
                        log.debug("SysUserServiceImpl insertSysOrgAndPositionForSync() insert sysPosition,param:{}", sysPosition);
                    } catch (Exception e) {
                        log.error("SysUserServiceImpl insertSysOrgAndPositionForSync() insert sysPosition,error:{}", e.getMessage());
                    }
                    if (null != sysPosition.getId() && sysPosition.getId() > 0) {
                        //岗位及员工关联信息
                        SysEmployeePosition sysEmployeePosition = new SysEmployeePosition();
                        sysEmployeePosition.setPositionId(sysPosition.getId());
                        sysEmployeePosition.setEmployeeId(employeeId);
                        sysEmployeePosition.setCreator(Constants.ORIGIN_SAP);
                        //主岗信息
                        if (null != vo.getIsPrimaryPos()) {//全量
                            sysEmployeePosition.setIsPrimaryPos(vo.getIsPrimaryPos());
                        } else {//增量
                            if (!ObjectUtils.isEmpty(vo.getOrgList())) {
                                vo.getOrgList().forEach(item -> {
                                    if (orgCode.equals(item.getOrgCode())) {
                                        sysEmployeePosition.setIsPrimaryPos(item.getIsPrimaryPos());
                                    }
                                });
                            }
                        }
                        try {
                            sysEmployeePositionDomain.insert(sysEmployeePosition);
                        } catch (Exception e) {
                            //方法可根据employeeId做更新操作
                            sysEmployeePosition.setModifier(Constants.ORIGIN_SAP);
                            sysEmployeePositionDomain.updateById(sysEmployeePosition);
                            log.error("SysUserServiceImpl insertSysOrgAndPositionForSync() insert sysEmployeePosition,error:{}", e.getMessage());
                        }
                    }
                }
            }
        }
    }

    /**
     * 从SAP同步用户信息时，没有角色信息
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @OperateLogAnnotation(resouceType = ResourceTypeEnum.SYNC_USER_EMPLOYEE, operateType = OperateTypeEnum.UPDATE)
    public BaseResult updateForSync(UpdateUserRequestForSyncVO vo) {
        if (ObjectUtils.isEmpty(vo) || null == vo.getUserId() || StringUtils.isEmpty(vo.getEmployeeCode())) {
            throw new BaseException(BaseErrorCode.USER_ID_OR_EMPLOYEE_CODE_IS_NULL.getCode(), BaseErrorCode.USER_ID_OR_EMPLOYEE_CODE_IS_NULL.getMessage());
        }
        SysUser oldUser = sysUserDomain.getByIdWithIsDeleted(vo.getUserId());
        if (ObjectUtils.isEmpty(oldUser)) {
            return BaseResult.buildSuccess();
        }
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(vo, sysUser);
        // 加密密码
//        try {
//            if (StringUtils.isNotEmpty(vo.getPasswd())) {
//                String passwordPlainText = AESUtils.decryptByComac(vo.getPasswd(), AESUtils.keySeed);
//                sysUser.setPasswd(SysUserPassWdSaltEnum.encrypt(passwordPlainText));
//            }
//        } catch (Exception e) {
//            log.error("updateForSync decryptByComac error:{}", e);
//        }
        //密码不更新
        sysUser.setPasswd(null);
        sysUser.setId(vo.getUserId());
        sysUser.setModifier(Constants.ORIGIN_SAP);
        sysUser.setGmtModified(LocalDateTime.now());
        sysUser.setIsDeleted(YesOrNo.N.name());
        sysUserDomain.updateByIdWithIsDeleted(sysUser);
        Long employeeId = null;
        SysEmployee oldEmployee = sysEmployeeDomain.selectByEmployeeCodeWithIsDeleted(oldUser.getEmployeeCode());
        if (ObjectUtils.isEmpty(oldEmployee)) {
            //员工表里无数据，新增
            SysEmployee employee = new SysEmployee();
            BeanUtils.copyProperties(vo, employee);
            employee.setCreator(Constants.ORIGIN_SAP);
            sysEmployeeDomain.insert(employee);
            employeeId = employee.getId();
        } else {//更新
            SysEmployee employee = new SysEmployee();
            BeanUtils.copyProperties(vo, employee);
            employee.setId(oldEmployee.getId());
            employee.setCreator(Constants.ORIGIN_SAP);
            employee.setModifier(Constants.ORIGIN_SAP);
            employee.setIsDeleted(YesOrNo.N.name());
            sysEmployeeDomain.updateByIdWithIsDeleted(employee);
            employeeId = oldEmployee.getId();
        }
        //员工和人员关系表更新
        SysUserEmployee userEmployee = new SysUserEmployee();
        userEmployee.setUserId(vo.getUserId());
        userEmployee.setEmployeeId(employeeId);
        userEmployee.setCreator(Constants.ORIGIN_SAP);
        if (null != vo.getUserId() && null != employeeId) {
            Integer count = sysUserEmployeeDomain.countByEmployeeIdAndUserId(userEmployee);
            if (null == count || count < 1) {
                sysUserEmployeeDomain.deleteByUserId(userEmployee.getUserId());
                sysUserEmployeeDomain.insert(userEmployee);
            }
        }
        // 删除缓存
        sysUserCacheService.deleteUserFromCacheByUserDelete(Collections.singletonList(vo.getUserId()));
        //关系数据通过关系接口进行修改
        return BaseResult.buildSuccess();
    }

    /**
     * 从SAP同步用户信息时，没有角色信息
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @OperateLogAnnotation(resouceType = ResourceTypeEnum.SYNC_USER_EMPLOYEE, operateType = OperateTypeEnum.DELETE)
    public BaseResult deleteForSync(DeleteUserRequestForSyncVO vo) {
        if (ObjectUtils.isEmpty(vo) || StringUtils.isEmpty(vo.getUserAccount())) {
            throw new BaseException(SysUserErrorCode.MISSING_REQUIRED_FIELD.getCode(), SysUserErrorCode.MISSING_REQUIRED_FIELD.getMessage());
        }
        SysUser oldUser = sysUserDomain.getByUserAccount(vo.getUserAccount());
        if (oldUser == null) {
            log.info("SysUserServiceImpl.deleteForSync oldUser no found");
            return BaseResult.buildSuccess();
        }
        Long userId = oldUser.getId();
        SysEmployee oldEmployee = sysEmployeeDomain.selectByEmployeeCode(oldUser.getEmployeeCode());
        if (ObjectUtils.isEmpty(oldEmployee) && null != userId) {
            //根据code未查到，根据关系表再查一次
            oldEmployee = sysUserEmployeeDomain.selectEmployeeByUserId(userId);
        }
        Long employeeId = null;
        if (!ObjectUtils.isEmpty(oldEmployee)) {
            employeeId = oldEmployee.getId();
        }
        //根据employeeId删除员工及员工关联关系(功能删除)
//        if (null != employeeId && employeeId > 0) {
//            delOrgAndPositionByEmployeeId(employeeId);
//        }
        //根据userId删除用户及用户关联关系
        if (null != userId && userId > 0) {
            SysUser sysUser = new SysUser();
            sysUser.setId(userId);
            sysUser.setIsDeleted(YesOrNo.Y.name());
            sysUser.setModifier(Constants.ORIGIN_SAP);
            sysUser.setGmtModified(LocalDateTime.now());
            sysUserDomain.updateById(sysUser);
            SysUserEmployee sysUserEmployee = new SysUserEmployee();
            sysUserEmployee.setUserId(userId);
            sysUserEmployee.setIsDeleted(YesOrNo.Y.name());
            sysUserEmployee.setModifier(Constants.ORIGIN_SAP);
            sysUserEmployee.setGmtModified(LocalDateTime.now());
            sysUserEmployeeDomain.updateSysUserEmployeeByUserId(sysUserEmployee);
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setIsDeleted(YesOrNo.Y.name());
            sysUserRole.setModifier(Constants.ORIGIN_SAP);
            sysUserRole.setGmtModified(LocalDateTime.now());
            sysUserRoleDomain.updateByUserId(sysUserRole);
            sysUserAppDomain.deleteByUserId(userId);
        }
        //删除员工岗位标签信息
        deleteLabelOrgByEmployeeId(employeeId);
        //删除缓存
        if (null != userId && userId > 0) {
            sysUserCacheService.deleteUserFromCacheByUserDelete(Collections.singletonList(userId));
        }
        return BaseResult.buildSuccess();
    }

    private void delOrgAndPositionByEmployeeId(Long employeeId) {
        SysEmployee sysEmployee = new SysEmployee();
        sysEmployee.setId(employeeId);
        sysEmployee.setIsDeleted(YesOrNo.Y.name());
        sysEmployee.setModifier(Constants.ORIGIN_SAP);
        sysEmployee.setGmtModified(LocalDateTime.now());
        sysEmployeeDomain.updateById(sysEmployee);
        SysEmployeeOrg sysEmployeeOrg = new SysEmployeeOrg();
        sysEmployeeOrg.setEmployeeId(employeeId);
        sysEmployeeOrg.setIsDeleted(YesOrNo.Y.name());
        sysEmployeeOrg.setModifier(Constants.ORIGIN_SAP);
        sysEmployeeOrg.setGmtModified(LocalDateTime.now());
        sysEmployeeOrgDomain.updateByEmployeeId(sysEmployeeOrg);
        SysEmployeePosition sysEmployeePosition = new SysEmployeePosition();
        sysEmployeePosition.setEmployeeId(employeeId);
        sysEmployeePosition.setIsDeleted(YesOrNo.Y.name());
        sysEmployeePosition.setModifier(Constants.ORIGIN_SAP);
        sysEmployeePosition.setGmtModified(LocalDateTime.now());
        sysEmployeePositionDomain.updateByEmployeeId(sysEmployeePosition);
    }

    private void deleteLabelOrgByEmployeeId(Long employeeId) {
        sysLabelOrgEmployeeDomain.deleteByEmployeeId(employeeId);
    }

    /**
     * 校验用户账号和手机去重,一个员工只能绑定一个用户账号
     *
     * @param userId      用户id
     * @param userAccount 用户账号
     * @param employeeId  员工账号
     */
    private void checkUserInfo(Long userId, String userAccount, Long employeeId) {
        // 校验用户账号
        checkUserAccount(userAccount);
        // 校验用户和员工的关联关系,一个员工只能有一个账号
        if (!ObjectUtils.isEmpty(employeeId)) {
            Long userIdByEmployeeId = sysUserEmployeeDomain.selectUserIdByEmployeeId(employeeId);
            if (!ObjectUtils.isEmpty(userIdByEmployeeId) && !userIdByEmployeeId.equals(userId)) {
                throw new BaseException(SysUserEmployeeErrorCode.USER_EMLOYEE_REPEAT.getCode(), SysUserEmployeeErrorCode.USER_EMLOYEE_REPEAT.getMessage());
            }
        }
        // 校验用户手机号
//        if (StringUtils.isNotEmpty(mobilePhone)) {
//            SysUser sysUser = new SysUser();
//            sysUser.setMobilePhone(mobilePhone);
//            Integer counts = sysUserDomain.countByPara(sysUser);
//            if (counts > 0) {
//                throw new BaseException(SysUserErrorCode.USER_MOBILE_PHONE_REPEAT.getCode(), SysUserErrorCode.USER_MOBILE_PHONE_REPEAT.getMessage());
//            }
//        }
    }

    private void checkUserAccount(String userAccount) {
        if (StringUtils.isNotEmpty(userAccount)) {
            // 不区分大小写，不区分是否逻辑删除，用户账户都不能重复
            userAccount = userAccount.toLowerCase();
            SysUser sysUser = new SysUser();
            sysUser.setUserAccount(userAccount);
            Integer counts = sysUserDomain.countByParaExtend(sysUser);
            if (counts > 0) {
                throw new BaseException(SysUserErrorCode.USER_ACCOUNT_REPEAT.getCode(), SysUserErrorCode.USER_ACCOUNT_REPEAT.getMessage());
            }
        }
    }

    /**
     * 校验用户账号和手机去重,一个员工只能绑定一个用户账号
     *
     * @param userAccount 用户账号
     * @param mobilePhone 手机号
     * @param employeeId  员工账号
     * @param passWd      密码
     */
    private void checkUserInfoForInsert(String userAccount, String mobilePhone, Long employeeId, String passWd) {
        // 校验用户账号
        checkUserAccount(userAccount);
        // 校验用户和员工的关联关系,一个员工只能有一个账号
        if (!ObjectUtils.isEmpty(employeeId)) {
            Long userIdByEmployeeId = sysUserEmployeeDomain.selectUserIdByEmployeeId(employeeId);
            if (!ObjectUtils.isEmpty(userIdByEmployeeId)) {
                throw new BaseException(SysUserEmployeeErrorCode.USER_EMLOYEE_REPEAT.getCode(), SysUserEmployeeErrorCode.USER_EMLOYEE_REPEAT.getMessage());
            }
        }
        // 校验用户手机号
        if (StringUtils.isNotEmpty(mobilePhone)) {
            SysUser sysUser = new SysUser();
            sysUser.setMobilePhone(mobilePhone);
            Integer counts = sysUserDomain.countByPara(sysUser);
            if (counts > 0) {
                throw new BaseException(SysUserErrorCode.USER_MOBILE_PHONE_REPEAT.getCode(), SysUserErrorCode.USER_MOBILE_PHONE_REPEAT.getMessage());
            }
        }
        // 密码不能为空
        if (null != passWd && passWd.isEmpty()) {
            throw new BaseException(SysUserErrorCode.PASS_WD_LOST.getCode(), SysUserErrorCode.PASS_WD_LOST.getMessage());
        }
    }

    /**
     * 批量删除用户
     *
     * @param userIdList 删除标识
     * @return 删除结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public BaseResult delete(List<Long> userIdList) {
        if (CollectionUtils.isEmpty(userIdList)) {
            log.info("SysUserServiceImpl delete userIdList is null");
            return BaseResult.buildError("参数不能为空");
        }
        for (Long userId : userIdList) {
            SysUser sysUser = new SysUser();
            sysUser.setId(userId);
            sysUser.setIsDeleted(YesOrNo.Y.name());
            sysUser.setGmtModified(LocalDateTime.now());
            sysUserDomain.updateById(sysUser);
            // 删除员工
            sysUserEmployeeService.deleteByUserId(userId);
            // 删除角色
            sysUserRoleService.delete(userId);
            // 删除租户登录权限
            sysUserAppDomain.deleteByUserId(userId);
            // 删除岗位标签
            SysEmployee sysEmployee = sysUserEmployeeDomain.selectEmployeeByUserId(userId);
            if (!Objects.isNull(sysEmployee)) {
                sysLabelOrgEmployeeDomain.deleteByEmployeeId(sysEmployee.getId());
            }

        }
        // 批量删除缓存
        sysUserCacheService.deleteUserFromCacheByUserDelete(userIdList);
        return BaseResult.buildSuccess();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public BaseResult revalidate(List<Long> userIdList) {
        if (CollectionUtils.isEmpty(userIdList)) {
            log.info("SysUserServiceImpl revalidateUser userIdList is null");
            return BaseResult.buildError("参数不能为空");
        }
        //恢复逻辑删除的数据
        for (Long userId : userIdList) {
            //根据userId查询最后修改时间
            List<Long> userIds = new ArrayList<>();
            LocalDateTime lastModifyTime = null;
            userIds.add(userId);
            Map<Long, SysUser> userMap = sysUserDomain.qryUserMapByIdList(userIds);
            if (!ObjectUtils.isEmpty(userMap)) {
                SysUser sysUserFromDB = userMap.get(userId);
                lastModifyTime = sysUserFromDB.getGmtModified();
            }
            SysUser sysUser = new SysUser();
            sysUser.setId(userId);
            sysUser.setIsDeleted(YesOrNo.N.name());
            sysUserDomain.updateByIdWithIsDeleted(sysUser);
            // 恢复用户员工关联
            sysUserEmployeeService.updateIsDeletedByUserIdLastModified(userId, lastModifyTime);
            // 恢复用户角色关联
            sysUserRoleService.updateIsDeletedByUserIdLastModified(userId, lastModifyTime);
            //增加登录权限sys_user_app
            //mom
            insertUser(sysUser, Constants.APP_MOM);
            //cmos
            insertUser(sysUser, Constants.APP_CMOS);
        }
        // 批量删除缓存
        sysUserCacheService.deleteUserFromCacheByUserDelete(userIdList);
        return BaseResult.buildSuccess();
    }

    /**
     * 批量激活
     *
     * @param paramVo 入参
     * @return 激活结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public BaseResult activate(List<Long> paramVo) {
        for (Long userId : paramVo) {
            SysUser sysUser = new SysUser();
            sysUser.setId(userId);
            sysUser.setUserState(SysUserStateEnum.ACTIVATE.getValue());
            sysUserDomain.updateById(sysUser);
        }
        // 删除缓存
        sysUserCacheService.deleteUserFromCacheByUserDelete(paramVo);
        return BaseResult.buildSuccess();
    }

    /**
     * 批量冻结
     *
     * @param paramVo 入参
     * @return 冻结结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public BaseResult freeze(List<Long> paramVo) {
        for (Long userId : paramVo) {
            SysUser sysUser = new SysUser();
            sysUser.setId(userId);
            sysUser.setUserState(SysUserStateEnum.FREEZE.getValue());
            sysUserDomain.updateById(sysUser);
        }
        // 删除缓存
        sysUserCacheService.deleteUserFromCacheByUserDelete(paramVo);
        return BaseResult.buildSuccess();
    }

    /**
     * 重置密码
     *
     * @param vo 员工列表
     * @return 重置结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public BaseResult<Boolean> resetPassWd(ResetUserPassWord vo) {
        log.info("重置密码的入参 passWd:{}", vo.getPasswd());
        SysUser sysUser = new SysUser();
        sysUser.setId(vo.getUserId());
        sysUser.setPasswd(SysUserPassWdSaltEnum.encrypt(vo.getPasswd()));
        sysUserDomain.updateById(sysUser);
        return BaseResult.buildSuccess();
    }

    /**
     * 用户信息更新
     *
     * @param vo 入参
     * @return 更新结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public BaseResult update(UpdateUserRequestVO vo) {
        Long userId = vo.getId();
        if (ObjectUtils.isEmpty(userId)) {
            throw new BaseException(BaseErrorCode.USER_ID_IS_NULL.getCode(), BaseErrorCode.USER_ID_IS_NULL.getMessage());
        }
        if (StringUtils.isEmpty(vo.getAppCode())) {
            return BaseResult.buildError(BaseErrorCode.APP_CODE_IS_NULL.getCode(), BaseErrorCode.APP_ID_IS_NULL.getMessage());
        }
        String userAccount = vo.getUserAccount();
        Long employeeId = vo.getEmployeeId();
        String mobilePhone = vo.getMobilePhone();
        SysUser user = sysUserDomain.getById(userId);
        // 预处理校验--用户账号
        if (user.getUserAccount().equals(vo.getUserAccount())) {
            userAccount = "";
        }
        // 预处理校验--员工工号
        if (StringUtils.isNotEmpty(user.getEmployeeCode()) && user.getEmployeeCode().equals(vo.getEmployeeCode().trim())) {
            employeeId = null;
        }
        // 预处理校验--手机号
        if (null == mobilePhone) {
            mobilePhone = "";
        }
        //  校验修改信息
        this.checkUserInfo(userId, userAccount, employeeId);
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(vo, sysUser);
        sysUserDomain.updateById(sysUser);
        // 员工和用户的关联关系
        if (!ObjectUtils.isEmpty(employeeId)) {
            // 先删除之前的关联关系
            sysUserEmployeeService.deleteByUserId(userId);
            // 重新关联
            sysUserEmployeeService.insert(userId, employeeId);
        }
        // 更新用户和角色的关联信息
        if (!CollectionUtils.isEmpty(vo.getRoleIdList())) {
            // 先删除之前的关联关系
            sysUserRoleDomain.invalidByUserIdAndAppCode(userId, vo.getAppCode());
            // 重新关联
            for (Long roleId : vo.getRoleIdList()) {
                sysUserRoleService.insert(userId, roleId);
            }
        }
        // 删除缓存
        sysUserCacheService.deleteUserFromCacheByUserUpdate(user);
        return BaseResult.buildSuccess();
    }

    /**
     * 用户列表分页接口(区分租户)
     *
     * @param vo 入参
     * @return 用户列表
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult selectPageByApp(SelectUserListByAppRequestVO vo) {
        return BaseResult.buildSuccess(sysUserDomain.selectPageByApp(vo));
    }

    /**
     * 用户列表分页接口
     *
     * @param vo 入参
     * @return 用户列表
     */
    @Override
    @Deprecated
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult selectPage(SelectUserListRequestVO vo) {
        return BaseResult.buildSuccess(sysUserDomain.selectPage(vo));
    }

    /**
     * 用户对象列表分页接口
     *
     * @param vo 入参
     * @return 用户列表
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult selectPageEntity(SelectUserListRequestVO vo) {
        return BaseResult.buildSuccess(sysUserDomain.selectPageEntity(vo));
    }

    @Override
    public SelectUserDetailResponseVO selectDetailByCode(SelectUserDetailByCodeRequestVO vo) {
        SysUser userCon = new SysUser();
        userCon.setEmployeeCode(vo.getUserCode());
        List<SysUser> userList = sysUserDomain.listByPara(userCon, new LinkedHashMap<>());
        SelectUserDetailResponseVO selectUserDetailResponseVO = new SelectUserDetailResponseVO();
        if (!userList.isEmpty()) {
            SysUser sysUser = userList.get(0);
            BeanUtils.copyProperties(sysUser, selectUserDetailResponseVO);
        }
        return selectUserDetailResponseVO;
    }


    @Override
    public UserBasicInfoVO selectByUserAccount(SelectUserRequestVO vo) {
        String userAccount = vo.getUserAccount();
        if (userAccount == null || userAccount.isEmpty()) {
            throw new RuntimeException("userAccount不能为空");
        }
        SysUser param = new SysUser();
        param.setUserAccount(userAccount);
        List<SysUser> userList = sysUserDomain.listByPara(param, new LinkedHashMap<>());
        if (userList == null) {
            return null;
        }
        SysUser sysUser = userList.get(0);
        UserBasicInfoVO info = new UserBasicInfoVO();
        info.setId(sysUser.getId());
        info.setUserAccount(sysUser.getUserAccount());
        info.setEmployeeCode(sysUser.getEmployeeCode());
        info.setMobilePhone(sysUser.getMobilePhone());
        info.setEmail(sysUser.getEmail());
        info.setUserName(sysUser.getUserName());

        return info;
    }

    @Override
    public BaseResult<Set<SelectResourceActionListVO>> selectResourceActionListByUser(SelectResourceActionListByUserReqVO vo) {
        SelectRoleListByUserRequestVO roleByUserVO = new SelectRoleListByUserRequestVO();
        long userId = vo.getUserId();
        String appCode = vo.getAppCode();
        roleByUserVO.setUserId(userId);
        roleByUserVO.setAppCode(appCode);
        List<String> roleList = sysUserDomain.selectRoleListByUser(roleByUserVO);
        Set<SelectResourceActionListVO> result = new HashSet<>();

        for (String roleCode : roleList) {
            SelectResourceActionListByRoleReqVO selectByRoleVO = new SelectResourceActionListByRoleReqVO();
            selectByRoleVO.setRoleCode(roleCode);
            selectByRoleVO.setAppCode(appCode);
            List<SelectResourceActionListVO> resourceActionList = sysRoleResourceActionDomain.selectResourceActionListByRoleReq(selectByRoleVO);
            result.addAll(resourceActionList);

        }

        return BaseResult.buildSuccess(result);

    }

    @Override
    public BaseResult authByUser(AuthByUserReqVO authVO) {
        boolean flag = false;
        long userId = authVO.getUserId();
        long resourceId = authVO.getResourceId();
        String actionCode = authVO.getActionCode();
        String appCode = authVO.getAppCode();

        SelectResourceActionListByUserReqVO vo = new SelectResourceActionListByUserReqVO();
        vo.setUserId(userId);
        vo.setAppCode(appCode);

        BaseResult<Set<SelectResourceActionListVO>> br = selectResourceActionListByUser(vo);
        Set<SelectResourceActionListVO> resourceActionList = br.getData();
        //检查用户包含的资源权限是否包含请求中的资源动作组
        for (SelectResourceActionListVO tmpVO : resourceActionList) {
            if (tmpVO.getResourceId() == resourceId && tmpVO.getActionCode().equals(actionCode)) {
                flag = true;
                break;
            }
        }

        if (flag) {
            return BaseResult.buildSuccess("User authorization success");
        } else {
            return BaseResult.buildError("User authorization failure");
        }
    }

    @Override
    public BaseResult selectUserEmployeeListByEmployeeCode(@RequestBody SelectUserListRequestVO vo) {
        List<EmployeeInfo> employeeList = sysUserDomain.selectUserEmployeeListByEmployeeCode(vo);
        return BaseResult.buildSuccess(employeeList);
    }

    @Override
    public BaseResult selectUserEmployeeListWithIsDeletedByEmployeeCode(@RequestBody SelectUserListRequestVO vo) {
        List<EmployeeInfo> employeeList = sysUserDomain.selectUserEmployeeListWithIsDeletedByEmployeeCode(vo);
        return BaseResult.buildSuccess(employeeList);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @OperateLogAnnotation(resouceType = ResourceTypeEnum.SYNC_EMPLOYEE_ORG_POS_REL, operateType = OperateTypeEnum.INSERT)
    public BaseResult addUserPositionOrgRel(@RequestBody AddPositionOrgRelRequestVO vo) {
        if (ObjectUtils.isEmpty(vo) || StringUtils.isEmpty(vo.getUserAccount())) {
            return BaseResult.buildError(BaseErrorCode.USER_ACCOUNT_IS_NULL.getCode(), BaseErrorCode.USER_ACCOUNT_IS_NULL.getMessage());
        }
        log.info("SysUserServiceImpl addUserPositionOrgRel param:{}", JSON.toJSONString(vo));
        //根据userAccount查询employeeId
        SelectOrgUserEmployeeVO param1 = new SelectOrgUserEmployeeVO();
        param1.setUserAccount(vo.getUserAccount());
        List<SysEmployee> employeeList = sysEmployeeDomain.selectListByUserAccount(param1);
        Long employeeId = null;
        if (!ObjectUtils.isEmpty(employeeList)) {
            employeeId = employeeList.get(0).getId();
        }
        //根据orgCode查询orgId
        SysOrg param2 = new SysOrg();
        param2.setOrgCode(vo.getOrgCode());
        SysOrg sysOrg = sysOrgDomain.selectOneByCondition(param2);
        Long orgId = null;
        if (!ObjectUtils.isEmpty(sysOrg)) {
            orgId = sysOrg.getId();
        }
        //根据positionCode查询positionId
        SysPosition param3 = new SysPosition();
        param3.setPosCode(vo.getPosCode());
        SysPosition sysPosition = sysPositionDomain.getPositionDetail(param3);
        Long posId = null;
        if (!ObjectUtils.isEmpty(sysPosition)) {
            posId = sysPosition.getId();
        }
        if (null == employeeId || employeeId <= 0) {
            return BaseResult.buildError(BaseErrorCode.EMPLOYEE_ID_IS_NULL.getCode(), BaseErrorCode.EMPLOYEE_ID_IS_NULL.getMessage());
        }
        //新增员工组织关系
        if (null != orgId && orgId > 0) {
            log.info("SysUserServiceImpl addUserPositionOrgRel employeeId:{},orgId:{}", employeeId, orgId);
            SysEmployeeOrg sysEmployeeOrg = new SysEmployeeOrg();
            sysEmployeeOrg.setEmployeeId(employeeId);
            sysEmployeeOrg.setOrgId(orgId);
            //主部门判断
            sysEmployeeOrg.setIsPrimaryOrg(((vo.getIsPrimary() == 0) ? "Y" : "N"));
            //先查询是否已存在
            Integer count = sysEmployeeOrgDomain.countByEmployeeIdAndOrgId(employeeId, orgId);
            if (null != count && count <= 0) {
                log.info("SysUserServiceImpl addUserPositionOrgRel insert employeeOrg:{}", JSON.toJSONString(sysEmployeeOrg));
                sysEmployeeOrg.setCreator(Constants.ORIGIN_SAP);
                sysEmployeeOrgDomain.insert(sysEmployeeOrg);
            }
        }
        //新增员工岗位关系
        if (null != posId && posId > 0) {
            log.info("SysUserServiceImpl addUserPositionOrgRel employeeId:{},posId:{}", employeeId, posId);
            SysEmployeePosition sysEmployeePosition = new SysEmployeePosition();
            sysEmployeePosition.setEmployeeId(employeeId);
            sysEmployeePosition.setPositionId(posId);
            //先查询是否存在
            String midParam = ((null == vo.getMid()) ? "0" : vo.getMid());
            Integer count = sysEmployeePositionDomain.countByMid(midParam);
            if (null != count && count <= 0) {
                //主岗判断
                sysEmployeePosition.setIsPrimaryPos(vo.getIsPrimary());
                sysEmployeePosition.setMid(vo.getMid());
                log.info("SysUserServiceImpl addUserPositionOrgRel insert employeePosition:{}", JSON.toJSONString(sysEmployeePosition));
            } else {
                //兼容mid为空时的BUG
                sysEmployeePosition.setIsDeleted("N");
                List<SysEmployeePosition> sysEmployeePositions = sysEmployeePositionDomain.listByPara(sysEmployeePosition, null);
                if (CollectionUtils.isEmpty(sysEmployeePositions)) {
                    return BaseResult.buildSuccess();
                }
                //处理异常数据
                sysEmployeePositions.forEach(i -> {
                    i.setIsDeleted("Y");
                    sysEmployeePositionDomain.updateById(i);
                });
                sysEmployeePosition.setIsPrimaryPos(vo.getIsPrimary());
                sysEmployeePosition.setMid(vo.getMid());
            }
            sysEmployeePosition.setCreator(Constants.ORIGIN_SAP);
            sysEmployeePositionDomain.insert(sysEmployeePosition);
        }
        return BaseResult.buildSuccess();
    }

    @Override
    public BaseResult<UserAllInfoResVo> selectUserAllInfoByUserIdOrUserCode(UserAllInfoRequestVO vo) {
        //参数校验
        if (null == vo || (null == vo.getUserId() && StringUtils.isEmpty(vo.getUserCode()))) {
            return BaseResult.buildError(BaseErrorCode.USER_ID_OR_USER_CODE_IS_NULL.getCode(),
                    BaseErrorCode.USER_ID_OR_USER_CODE_IS_NULL.getMessage());
        }
        SysUser sysUser;
        if (null != vo.getUserId()) {
            sysUser = sysUserDomain.getById(vo.getUserId());
        } else {
            sysUser = sysUserDomain.getOneByEmployeeCode(vo.getUserCode());
        }
        BaseResult<UserAllInfoResVo> baseResult = new BaseResult<>();
        if (null == sysUser) {
            baseResult.setCode(BaseErrorCode.USER_NOT_EXISTS.getCode());
            baseResult.setMessage(BaseErrorCode.USER_NOT_EXISTS.getMessage());
            return baseResult;
        }
        UserAllInfoResVo userAllInfoResVo = new UserAllInfoResVo();
        userAllInfoResVo.setUserId(sysUser.getId());
        userAllInfoResVo.setUserCode(sysUser.getUserAccount());
        userAllInfoResVo.setUserName(sysUser.getUserName());
        userAllInfoResVo.setUserAccount(sysUser.getUserAccount());
        //部门信息查询
        SysEmployee sysEmployee = sysEmployeeDomain.selectByEmployeeCode(sysUser.getEmployeeCode());
        if (null != sysEmployee) {
            Long primaryOrgId = sysEmployeeOrgDomain.selectPrimaryOrgIdListByEmployeeId(sysEmployee.getId());
            Optional<SysOrg> optionalSysOrg = Optional.ofNullable(sysOrgDomain.selectByOrgId(primaryOrgId));
            if (optionalSysOrg.isPresent()) {
                //部门信息
                userAllInfoResVo.setOrgId(optionalSysOrg.get().getId());
                userAllInfoResVo.setOrgCode(optionalSysOrg.get().getOrgCode());
                userAllInfoResVo.setOrgName(optionalSysOrg.get().getOrgName());
                //上级部门信息
                optionalSysOrg.map(SysOrg::getParentId).ifPresent(parentId ->
                        Optional.ofNullable(sysOrgDomain.selectByOrgId(parentId)).ifPresent(parentOrg -> {
                            userAllInfoResVo.setSecondOrgId(parentId);
                            userAllInfoResVo.setSecondOrgCode(parentOrg.getOrgCode());
                            userAllInfoResVo.setSecondOrgName(parentOrg.getOrgName());
                        }));
                //公司信息
                List<SysOrg> orgList = sysOrgDomain.selectOrgIdListRecursiveToRoot(optionalSysOrg.get().getId());
                if (CollectionUtils.isEmpty(orgList)) {
                    baseResult.setData(userAllInfoResVo);
                    return baseResult;
                }
                int index;
                if (orgList.size() > 1) {
                    index = 1;
                } else {
                    index = 0;
                }
                userAllInfoResVo.setCompanyId(orgList.get(index).getId());
                userAllInfoResVo.setCompanyCode(orgList.get(index).getOrgCode());
                userAllInfoResVo.setCompanyName(orgList.get(index).getOrgName());
            }
        }
        baseResult.setCode(200);
        baseResult.setData(userAllInfoResVo);
        return baseResult;
    }
}
